import { SchemaService } from './../service/schema';
import { Context } from 'egg';

import { AuthenticationClient } from 'authing-js-sdk';
import {
  Controller,
  Get,
  Provide,
  Inject,
  Post,
  Body,
  Validate,
  ALL,
  Headers,
} from '@midwayjs/decorator';
import { SchemaSaveDTO } from '../dto/schema';

@Provide()
@Controller('/api/schema/')
export class SchemaController {
  @Inject()
  ctx: Context;

  @Inject()
  schemaService: SchemaService;

  @Get('/getLatestOne')
  async home() {
    const result = await this.schemaService.getLatestOne();
    return result;
  }

  @Post('/save')
  @Validate()
  async save(
    @Body(ALL) bodyObj: SchemaSaveDTO,
    @Headers('token') token: string
  ) {
    const authing = new AuthenticationClient({
      appId: '61af70d5204cec9a542d2af5',
      appHost: 'https://reactblog.authing.cn',
      token,
    });
    const user = await authing.getCurrentUser();

    if (user?.username === 'aicherish') {
      const result = await this.schemaService.save(bodyObj.schema);
      return result;
    }
    return { errno: 0, message: '您没有保存权限' };
  }
}
